/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 */
package cn.net.ecode.modules.gen.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.gen.entity.GenTable;
import cn.net.ecode.modules.gen.entity.GenTableColumn;
import cn.net.ecode.modules.gen.service.GenTableService;
import cn.net.ecode.modules.gen.util.GenUtils;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.utils.UserUtils;

/**
 * 生成表Controller
 * @author ThinkGem
 * @version 2014-9-9
 */
@Controller
@RequestMapping(value = "${adminPath}/gen/genTable")
public class GenTableController extends BaseController {

	@Autowired
	private GenTableService genTableService;
	
	@ModelAttribute
	public GenTable get(String tableName) {
		GenTable entity = null;
		if (StringUtils.isNotBlank(tableName)){
			entity = genTableService.get(tableName);
		}
		if (entity == null){
			entity = new GenTable();
		}
		return entity;
	}
	
	@RequiresPermissions("gen:genTable:view")
	@RequestMapping(value = {"list", ""})
	public String list(GenTable genTable, Model model) {
		return "modules/gen/genTableList";
	}
	
	@RequiresPermissions("gen:genTable:view")
	@ResponseBody
	@RequestMapping(value = {"listData"})
	public Page<GenTable> listData(GenTable genTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isSuperAdmin()){
			genTable.setCreateBy(user);
		}
        Page<GenTable> page = genTableService.findPage(new Page<GenTable>(request, response), genTable); 
        return page;
	}
	
	@RequiresPermissions("gen:genTable:view")
	@RequestMapping(value = "form")
	public String form(GenTable genTable, Model model) {
        boolean flag = genTable.getIsNewRecord();
		// 验证表是否存在
		if (genTable.getIsNewRecord() && StringUtils.isNotBlank(genTable.getTableName()) && !genTableService.checkTableName(genTable.getTableName())){
			addMessage(model, "下一步失败！" + genTable.getTableName() + " 表已经添加！");
			genTable.setTableName(StringUtils.EMPTY);
		}
		// 获取物理表字段
		else{
			genTable = genTableService.getTableFormDb(genTable);
			genTable.setIsNewRecord(genTable.getIsNewRecord());
			if(flag){genTable.setIsNewRecord(flag);}
		}
		model.addAttribute("genTable", genTable);
		model.addAttribute("config", GenUtils.getConfig());
		
		// 设置默认包路径
		if (StringUtils.isBlank(genTable.getPackageName())){
			String defaultPackageName = Global.getConfig("gen.defaultPackageName");
			if (StringUtils.isNotBlank(defaultPackageName)){
				genTable.setPackageName(defaultPackageName);
			}else{
				genTable.setPackageName("cn.net.ecode.modules");
			}
		}
		
		// 设置默认模块名
		if (StringUtils.isBlank(genTable.getModuleName())){
			genTable.setModuleName(StringUtils.substringBefore(genTable.getTableName(), "_"));
		}

		// 获取物理表列表
		if (StringUtils.isBlank(genTable.getTableName())){
			List<GenTable> tableList = genTableService.findTableListFormDb(new GenTable());
			model.addAttribute("tableList", tableList);
		}
		
		return "modules/gen/genTableForm";
	}

	@RequiresPermissions("gen:genTable:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(GenTable genTable, Model model, RedirectAttributes redirectAttributes) {
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, genTable)){
			return renderResult(Global.FALSE, message.toString());
		}
		boolean existsPk = false, existsNull = false, existsInsert = false, 
				existsUpdate = false, existsList = false, existsQuery = false;
		for (GenTableColumn c : genTable.getColumnList()){
			if (Global.YES.equals(c.getIsPk())){
				existsPk = true;
			}
			if (Global.YES.equals(c.getIsNull())){
				existsNull = true;
			}
			if (Global.YES.equals(c.getIsInsert())){
				existsInsert = true;
			}
			if (Global.YES.equals(c.getIsUpdate())){
				existsUpdate = true;
			}
			if (Global.YES.equals(c.getIsList())){
				existsList = true;
			}
			if (Global.YES.equals(c.getIsQuery())){
				existsQuery = true;
			}
		}
		if (!existsPk || !existsNull || !existsInsert || !existsUpdate || !existsList || !existsQuery){
			return renderResult(Global.FALSE, "每一列复选按钮必须选择一项！");
		}
		genTableService.save(genTable);
		String msg = "保存表'" + genTable.getTableName() + "'成功";
		// 如果设置生成标记，则编译或生成代码
		if (StringUtils.inString(genTable.getFlag(), "1", "2")){
			String result = genTableService.generateCode(genTable);
			String flagMsg = ("1".equals(genTable.getFlag()) ? "编译" : "生成");
			msg = "posfull:" + flagMsg + "'" + genTable.getTableName() + "'成功: <br/>" + result;
		}
		return renderResult(Global.TRUE, msg);
	}
	
	@RequiresPermissions("gen:genTable:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(GenTable genTable, RedirectAttributes redirectAttributes) {
		genTableService.delete(genTable);
		return renderResult(Global.TRUE, "删除表成功");
	}

}
